from rest_framework import serializers
from .models import Product, ProductFile, Category


class CategorySerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['id', 'name', 'title', 'description', 'cover_image', 'children']

    def get_children(self, obj):
        children = obj.children.all()
        if children:
            return CategorySerializer(children, many=True).data
        return None


class ProductFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductFile
        fields = ['id', 'product', 'name', 'download_type', 'file']


class ProductDetailSerializer(serializers.ModelSerializer):
    downloads = ProductFileSerializer(many=True, read_only=True)  # 自动关联产品的文件列表

    class Meta:
        model = Product
        fields = ['id', 'name', 'brief_description', 'detailed_description', 'product_info', 'technical_data',
                  'video_links', 'downloads']


class ProductListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'brief_description', 'detailed_description']
